<template>
  <div class="pagination">
    <button @click="changePageNo(pageNo - 1)" :disabled="pageNo === 1">
      上一页
    </button>
    <button v-show="startAndEnd.start > 1">1</button>
    <span v-show="startAndEnd.start > 2">...</span>
    <button
      :class="{ active: pageNo === index + startAndEnd.start }"
      @click="changePageNo(index + startAndEnd.start)"
      v-for="(_, index) in startAndEnd.end - startAndEnd.start + 1"
      :key="_"
    >
      {{ index + startAndEnd.start }}
    </button>
    <span>...</span>
    <button>{{ totalPage }}</button>
    <button
      @click="changePageNo(pageNo + 1)"
      :disabled="pageNo === startAndEnd.end"
    >
      下一页
    </button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: {
    total: {
      //总商品数量
      type: Number,
      default: 1,
    },
    pageNo: {
      //当前页码
      type: Number,
      default: 1,
    },
    pageSize: {
      //每页商品数量
      type: Number,
      default: 0,
    },
    continues: {
      //连贯页码
      type: Number,
      default: 3,
    },
  },
  computed: {
    //总页码数
    totalPage() {
      //父组件传过来的数据，就相当于当前组件中data的数据
      let { total, pageSize } = this
      return Math.ceil(total / pageSize)
    },
    //计算连贯页码的起始和结束
    startAndEnd() {
      let { pageNo, continues, totalPage } = this
      let start, end
      if (continues > totalPage) {
        //如果连贯页码大于总的页码数量
        start = 1 //起始页就是1
        end = totalPage //结束页就是总页码
      } else {
        start = pageNo - Math.trunc(continues / 2)
        end = pageNo + Math.trunc(continues / 2)
      }
      if (start < 1) {
        start = 1
        end = continues
      }
      if (end > totalPage) {
        end = totalPage
        start = totalPage - continues + 1
      }
      return { start, end }
    },
  },
  methods: {
    changePageNo(pageNo) {
      this.$emit('chagne-pageno', pageNo)
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
